<template>
  <div>
    <el-card class="margin-30" shadow="never">
      <div slot="header">
        <el-button type="primary" size="small" @click="openDialog('')">新增</el-button>
      </div>
      <el-table :data="brandList" border stripe>
        <el-table-column
          fixed="left"
          type="index"
          align="center"
          label="序号"
          width="60"
        />
        <el-table-column
          prop="name"
          align="center"
          label="品牌名称"
          width="150"
        />
        <el-table-column
          align="center"
          label="展示状态"
          width="200"
        >
          <template slot-scope="scope">
            <span>是否展示：</span>
            <el-switch v-model="scope.row.showStatus" :active-value="1" :inactive-value="0" @change="switchStatus($event,scope.row.id)" />
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="logo"
          width="200"
        >
          <template slot-scope="scope">
            <img width="100" height="100" :src="scope.row.logo" alt="">
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="专区大图"
          width="200"
        >
          <template slot-scope="scope">
            <img width="100" height="100" :src="scope.row.bigPic" alt="">
          </template>
        </el-table-column>
        <el-table-column
          prop="brandStory"
          align="center"
          label="品牌故事"
          width="200"
        />
        <el-table-column
          prop="createTime"
          align="center"
          label="创建时间"
          width="200"
        />
        <el-table-column
          prop="sort"
          align="center"
          label="排序"
          width="150"
        />
        <el-table-column
          prop="productCount"
          align="center"
          label="产品数量"
          width="100"
        />
        <el-table-column
          align="center"
          label="是否品牌制造商"
          width="100"
        >
          <template slot-scope="scope">
            {{ scope.row.factoryStatus ?'是':'不是' }}
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          align="center"
          label="操作"
          width="150"
        >
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="openDialog(scope.row.id,scope.row)">编辑</el-button>
            <el-button type="text" style="color:red;" size="mini" @click="deleteBrand(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        style="margin-top:10px;"
        :current-page="pagination.start"
        :page-sizes="pagination.sizes"
        :page-size="pagination.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog
      width="70%"
      title="品牌详情"
      :visible.sync="dialogVisible"
      @close="closeDialog"
    >
      <el-form ref="form" :model="form" :rules="rules" label-position="top" size="mini">
        <el-row :gutter="20">
          <el-col :span="7" :offset="0">
            <el-form-item label="品牌名称" prop="name">
              <el-input v-model="form.name" placeholder="品牌名称" style="width:100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="4">
            <el-form-item label="首字母">
              <el-input v-model="form.firstLetter" placeholder="首字母" style="width:100%;" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="7" :offset="0">
            <el-form-item label="排序">
              <el-input v-model="form.sort" placeholder="排序" style="width:100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="4">
            <el-form-item label="产品数量" prop="productCount">
              <el-input v-model="form.productCount" placeholder="产品数量" style="width:100%;" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="7" :offset="0">
            <el-form-item label="是否展示" size="mini">
              <el-switch v-model="form.showStatus" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="4">
            <el-form-item label="是否为品牌制造商" size="mini">
              <el-switch v-model="form.factoryStatus" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="7" :offset="0">
            <el-form-item label="品牌故事" size="mini">
              <el-input v-model="form.brandStory" placeholder="品牌故事" size="mini" />
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="4">
            <el-form-item label="产品评论数量" prop="productCommentCount">
              <el-input v-model="form.productCommentCount" placeholder="产品评论数量" style="width:100%;" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="上传专区大图" size="mini">
              <el-upload
                class="avatar-uploader"
                :action="uploadImageUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="token"
                @click.native="sureClickUpload(true)"
              >
                <img v-if="form.bigPic" :src="form.bigPic" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="上传logo" size="mini">
              <el-upload
                class="avatar-uploader"
                :action="uploadImageUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="token"
                @click.native="sureClickUpload(false)"
              >
                <img v-if="form.logo" :src="form.logo" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUpdate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  findBrandByPage as findBrandByPageApi,
  delBrand as delBrandApi,
  addBrand as addBrandApi,
  updateBrand as updateBrandApi,
  switchShowStatus as switchShowStatusApi
} from '@/api/product/brand'
import mix from '@/mixin'
export default {
  name: 'BrandManage',
  mixins: [mix],
  data() {
    return {
      brandList: [],
      dialogVisible: false,
      form: {
        factoryStatus: 1,
        showStatus: 1,
        bigPic: '',
        logo: '',
        productCount: 0,
        productCommentCount: 0
      },
      rules: {
        name: [{ required: true, trigger: 'blur', message: '请输入品牌名称' }],
        productCount: [
          { required: true, trigger: 'blur', message: '请输入产品数量' },
          { pattern: /^\+?[1-9]\d*$/, trigger: 'blur', message: '产品数量必须大于0的数字' }
        ],
        productCommentCount: [
          { required: true, trigger: 'blur', message: '请输入产品评论数量' },
          { pattern: /^\+?[1-9]\d*$/, trigger: 'blur', message: '产品评论数量必须大于0的数字' }
        ]
      },
      flag: true, // true为点击的是专区大图，false为点击的是logo
      id: ''
    }
  },
  created() {
    this.getBrandList()
  },
  methods: {
    // 更改品牌的显示和隐藏
    switchStatus(e, id) {
      switchShowStatusApi({
        status: e,
        id: id
      })
        .then(res => {
          const { message, success } = res
          if (success) {
            this.$message.success('更改成功!')
            this.getBrandList()
          } else {
            this.$message.error(message)
          }
        })
    },
    // 确定点击的是哪一个上传图片
    sureClickUpload(flag) {
      this.flag = flag
    },
    // 缩略图文件上传成功时候的钩子函数
    handleAvatarSuccess(res, file, fileList) {
      const { success, message, data } = res
      if (success) {
        if (this.flag) { // 为真专区大图
          this.form.bigPic = data.fileUrl
        } else { // logo
          this.form.logo = data.fileUrl
        }
      } else {
        this.$message.error(message)
      }
    },
    // 在文件上传之前的钩子函数
    beforeAvatarUpload(file) {
      const isLt1dot5M = file.size / 1024 / 1024 < 1.5
      var reg = /^image\/(jpe?g|png|webp|gif)$/

      const isImage = reg.test(file.type)
      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt1dot5M) {
        this.$message.error('上传头像图片大小不能超过 1.5MB!')
      }
      return isImage && isLt1dot5M
    },
    // 打开弹框
    openDialog(id, form) {
      this.dialogVisible = true
      this.id = id
      if (id) {
        this.form = Object.assign({}, form)
      }
    },
    // 保存操作
    saveUpdate() {
      this.$refs.form.validate((valid, error) => {
        if (valid) { // 验证通过
          var api = null
          if (this.id) { // 修改操作
            // this.form.id = this.id
            api = updateBrandApi
          } else {
            api = addBrandApi
          }
          api(this.form)
            .then(res => {
              const { success, message } = res
              if (success) {
                if (this.id) {
                  this.$message.success('更新品牌成功!')
                } else {
                  this.$message.success('新增品牌成功!')
                }
                this.dialogVisible = false
                this.getBrandList()
              } else {
                this.$message.error(message)
              }
            })
        } else { // 验证失败
          for (var key in error) {
            if (error[key]) {
              const message = error[key][0].message
              this.$message.error(message)
              return
            }
          }
        }
      })
    },
    // 关闭弹框
    closeDialog() {
      this.dialogVisible = false
      this.form = this.$options.data().form
    },
    // 删除品牌
    deleteBrand(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delBrandApi(id)
          .then(res => {
            const { message, success } = res
            if (success) {
              this.$message.success('删除成功!')
              this.getBrandList()
            } else {
              this.$message.error(message)
            }
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 获取品牌列表
    getBrandList() {
      findBrandByPageApi(this.pagination.start, this.pagination.limit)
        .then(res => {
          const { message, data, success } = res
          if (success) {
            this.brandList = data.rows
            this.pagination.total = data.total
          } else {
            this.$message.error(message)
          }
        })
    },
    // 改变limit一页多少条数据
    handleSizeChange(e) {
      this.pagination.limit = e
      this.pagination.start = 1
      this.getBrandList()
    },
    // 改变当前页数start
    handleCurrentChange(e) {
      this.pagination.start = e
      this.getBrandList()
    }
  }
}
</script>

<style lang="scss" scoped>
.bold{
  font-weight: 700;
  margin-bottom: 30px;
}
::v-deep .el-form-item__label{
  transform: translateX(100px);
  font-weight: 700;
}
.avatar-uploader{
    transform: translate(220px, -35px);

}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
